package dao

import (
	"errors"
	"time"
	"user_srv/model"
	"user_srv/user"
)

// 个人成就规则添加
func CreateAchievementRule(in *user.CreateAchievementRuleRequest) (*model.AchievementRule, error) {
	rule := model.AchievementRule{
		Name:      in.Name,
		RuleDesc:  in.RuleDesc,
		Condition: in.Condition,
		Reward:    in.Reward,
		Status:    uint(in.Status),
	}
	err := rule.CreateAchievementRule()
	if err != nil {
		return nil, errors.New("成就规则添加失败")
	}
	return &rule, err
}

// 个人成就添加
func CreateAchievement(in *user.CreateAchievementRequest) (*model.Achievement, error) {
	lightedTime, err := time.Parse(time.DateTime, in.LightedTime)
	if err != nil {
		return nil, errors.New("时间格式不正确")
	}
	achievement := model.Achievement{
		UserId:            uint(in.UserId),
		RuleId:            uint(in.RuleId),
		AchievementName:   in.AchievementName,
		AchievementDesc:   in.AchievementDesc,
		AchievementImages: in.AchievementImages,
		IsLighted:         uint(in.IsLighted),
		LightedTime:       lightedTime,
		Status:            uint(in.Status),
	}
	err = achievement.CreateAchievement()
	if err != nil {
		return nil, errors.New("个人成就添加失败")
	}
	return &achievement, err
}

// 点亮成就
func LightAchievement(in *user.LightAchievementRequest) (*model.Achievement, error) {
	var achievement model.Achievement
	achievement.AchievementName = in.AchievementName
	achievement.Id = uint(in.Id)
	lightedTime, err := time.Parse(time.DateTime, in.LightedTime)
	if err != nil {
		return nil, errors.New("时间格式不正确")
	}
	err = achievement.GetAchievementByName(in.AchievementName)
	if err != nil {
		return nil, errors.New("该成就不存在，禁止修改")
	}
	achievement.IsLighted = uint(in.IsLighted)
	achievement.LightedTime = lightedTime
	achievement.Status = uint(in.Status)
	err = achievement.LightAchievement(int(in.Id))
	if err != nil {
		return nil, errors.New("点亮成就失败")
	}
	return &achievement, err
}

// 个人成就展示
func GetAchievementList(in *user.GetAchievementListRequest) ([]*user.AchievementList, error) {
	var achi model.Achievement
	list, err := achi.GetAchievementList(int(in.Status))
	if err != nil {
		return nil, errors.New("个人成就列表展示失败")
	}
	var Achievements []*user.AchievementList
	for _, ach := range list {
		lists := user.AchievementList{
			UserId:            int64(ach.UserId),
			RuleId:            int64(ach.RuleId),
			AchievementName:   ach.AchievementName,
			AchievementDesc:   ach.AchievementDesc,
			AchievementImages: ach.AchievementImages,
			IsLighted:         int64(ach.IsLighted),
			LightedTime:       ach.LightedTime.Format("2006-01-02 15:04:05"),
			Status:            int64(ach.Status),
		}
		Achievements = append(Achievements, &lists)
	}
	return Achievements, err
}
